from helpers import updateInfo
import urllib
from google.appengine.api import urlfetch

class Insights(object):
    """ Represents a I4S downloaded CSV file with parsing """
    kResults = {}
    prevlastDate=""
    lastDate=""
    regionsList=[]
    relatedList=[]
    # Array to calculate
    daysChange=[]
    last30DaysChange=[]
    
    
    def __init__(self, sQuery):
        """Initialize and send the query off to google"""
        self.regionsList=[]
        self.relatedList=[]
        # Array to calculate
        self.daysChange=[]
        self.last30DaysChange=[]
        
        url = self.get_url(sQuery)
        result = urlfetch.fetch(url=url, headers={'Cookie': updateInfo.getSID()})
        sContent=result.content
        sContent=sContent.decode("UTF-16")
        
        self.parse(sContent)

    def parse(self, sContent):
        """Parse the results from Google insights CSV into logical sections. """
        """ Currently only using the 'trend' section of the report """

        kSections    = {
            'trend':        'Interest over time',
            # Other sections currently not being used:
            'regions':    'Top regions for',
            #'cities':        'Top cities for',
            'related':    'Top searches for'
            #,
            #'rising':        'Rising searches for'
        }
        # Split content by \n\r
        aParts = sContent.split('\n\r')
                
        for sPart in aParts:

            for sSection, sFind in kSections.iteritems():
                if sPart.find(sFind) != -1:
                    self.parse_section( sPart, sSection )


    def parse_section(self, sPart, sSection):
        """Parse a section and add it to our results"""

        aLines        = sPart.strip().split('\n')
        aHeaders    = ['trend', 'regions', 'cities']
        nStart        = 1

        self.kResults[sSection] = {}

        # If this section has another header bump it down another line
        if sSection in aHeaders:
            nStart = 2
        
        xVal1=""
        
        # Number of related searches and regions to save
        listLengthMax=8
        
        listLengthCurr=0
        for i in xrange(nStart, len(aLines)):
            checkArr=aLines[i].split('\t')
            # Making sure format is valid and not adding days without data
            if len(checkArr)<>2 or " " in checkArr[1]:
                continue
                
            if sSection in "trend":
                self.prevlastDate=xVal1
            
            xVal1, xVal2= checkArr
            
            if sSection in "regions":
                if listLengthCurr<listLengthMax:
                    self.regionsList.append(xVal1)
                
            if sSection in "related":
                if listLengthCurr<listLengthMax:
                    self.relatedList.append(xVal1)
            
            self.kResults[sSection][xVal1] = xVal2

            if sSection in "trend":
                self.daysChange.append(float(xVal2))
            
            listLengthCurr+=1
            
        # Update lastDate var to hold the last day Google Insights provide 
        # data for the keyword
        
        if sSection in "trend":
            self.lastDate=xVal1


    def section(self, sSection):
        """Return the results for a given section. Valid sections are:

                - trend
                - regions
                - cities
                - related
                - rising
        """

        if sSection in self.kResults.keys():
            return self.kResults[sSection]

        raise ValueError, "Nothing know about section '%s'" % (sSection)

    
    def get_url(self, sQuery):
    
        """Returns a URL to retrieve for a given query"""
        
        sURL="http://www.google.com/insights/search/overviewReport?q=%(querytext)s&date=" % {'querytext': (urllib.quote(sQuery)) }
        sURL=sURL+"today%203-m&cmpt=q&content=1&export=2"
        return sURL
        
    def printLastDate(self):
        """ Return the last day data is available for the specific keyword """
        return self.lastDate
        
    def printprevLastDate(self):
        """ Return the last day data is available for the specific keyword """
        return self.prevlastDate
        
    def getTopRegionsList(self):
        """ Return the top regions list """
        return self.regionsList
        
    def getRelatedSearches(self):
        """ Return the related searched list """
        return self.relatedList
    
    def getLast30Days(self):
        """ Return a list with the last 30 days """
        totalLength=len(self.daysChange)
        if totalLength > 36:
            index=totalLength-36
            self.last30DaysChange=self.daysChange[index:totalLength]
        else :
            self.last30DaysChange=self.daysChange
        return self.last30DaysChange

    def get30DaysChange(self):
        """ Return a list with the last 30 days change percentage number (legendary) """
        if len(self.daysChange)<31:
            return 1.0
            
        if self.daysChange[len(self.daysChange)-31]==0:
            self.daysChange[len(self.daysChange)-31]=1
            
        return round(float(self.daysChange[len(self.daysChange)-1])/float(self.daysChange[len(self.daysChange)-31]),2)
        
    def get90DaysChange(self):
        """ Return a list with the last 90 days change percentage number (legendary) """
        if len(self.daysChange)<1:
            return 1.0
        
        if self.daysChange[0]==0:
            self.daysChange[0]=1
            
        return round(float(self.daysChange[len(self.daysChange)-1])/float(self.daysChange[0]),2)